package com.ttg.utils.connection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.conn.HttpClientConnectionManager;

import java.util.concurrent.TimeUnit;

public class IdleConnectionMonitorThread extends Thread {

    private final Log logger = LogFactory.getLog (IdleConnectionMonitorThread.class);
    private final HttpClientConnectionManager connMgr;
    private int idletime = 30;
    private volatile boolean shutdown;

    public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idletime) {
        this.connMgr = connMgr;
        this.idletime = idletime;
    }

    public void setIdletime(int idletime) {
        this.idletime = idletime;
    }

    public void run() {
        while(true) {
            try {
                if(!this.shutdown) {
                    synchronized(this) {
                        this.wait(5000L);
                        this.connMgr.closeExpiredConnections();
                        this.connMgr.closeIdleConnections((long)this.idletime, TimeUnit.SECONDS);
                        continue;
                    }
                }
            } catch (InterruptedException var4) {
                logger.error(var4);
            }

            return;
        }
    }

    public void shutdown() {
        this.shutdown = true;
        synchronized(this) {
            this.notifyAll();
        }

        logger.info("Shutdown IdleConnectionMonitorThread completed");
    }
}
